//IE8需要引入Promise模块

(function (module) {
    module.FetchHelper = {
        getJson: function (url) {
            var dtd = $.Deferred();
            var _self = this;
            $.getJSON(url, null, function (data) {
                _self.handleResponse(dtd, data);
            });
            return dtd.promise();
        },
        postJson: function (url, body) {
            return this.post(url, body, {
                contentType: 'application/json; charset=utf-8'
            })
        },
        post: function (url, body, options) {
            options = options || {};
            options.dataType = options.dataType || 'json';
            var dtd = $.Deferred();
            var _self = this;
            var params = {
                url: url,
                type: 'POST',
                data: typeof (body) === 'string' ? body : JSON.stringify(body),
                dataType: options.dataType,
                success: function (data) {
                    _self.handleResponse(dtd, data);
                }
            };
            if (typeof(options.contentType) !== 'undefined') {
                params.contentType = options.contentType;
            }
            $.ajax(params);
            return dtd.promise();
        },
        handleResponse: function (dtd, data) {
            if (data) {
                if (data.code == 1) {
                    if (data.data) {
                        dtd.resolve(data.data);
                    } else {
                        dtd.resolve();
                    }
                } else {
                    dtd.reject(data);
                }
            } else {
                dtd.reject({
                    code: 500,
                    msg: '网络故障'
                });
            }
        }
    };
})(window);
